package com.zhj.juc.demo2;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @PackageName:com.zhj.juc.demo2
 * @ClassName:Test3
 * @auter: 朱慧杰
 * @date:2020/7/23 0023 9:39
 **/
public class Test3 {

    public static void main(String[] args) {
        Data3 data = new Data3();

        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                data.pringA();
            }
        },"A").start();

        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                data.pringB();
            }
        },"B").start();

        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                data.pringC();
            }
        },"C").start();

    }

}


class Data3 {
    private int number = 1;

    private Lock lock = new ReentrantLock();
    // 精确调用，生产线
    private Condition condition1 = lock.newCondition();
    private Condition condition2 = lock.newCondition();
    private Condition condition3 = lock.newCondition();

    public void pringA() {
        lock.lock();
        try {
            // 业务
            while (number!=1) {
                condition1.await();
            }
            System.out.println(Thread.currentThread().getName() + " => A");
            number = 2;
            condition2.signal();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void pringB() {
        lock.lock();
        try {
            // 业务
            while (number!=2) {
                condition2.await();
            }
            System.out.println(Thread.currentThread().getName() + " => B");
            number = 3;
            condition3.signal();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void pringC() {
        lock.lock();
        try {
            // 业务
            while (number!=3) {
                condition3.await();
            }
            System.out.println(Thread.currentThread().getName() + " => C");
            number = 1;
            condition1.signal();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}
